package com.neuedu.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServerSocket {


    private String ip = "192.168.70.101";
    private Integer port = 9999;


    public MyServerSocket() throws IOException {
        //启动一个服务器
        ServerSocket server = new ServerSocket(port);

        //监听客户端的请求 阻塞的方法, 直到有客户端请求
        System.out.println("程序有监听: "+port);
        while (true){
            Socket client = server.accept();
            if(client != null){
                new Thread(()->{
                    //让子线程处理  client
                    try {
                        InputStream input = client.getInputStream();
                        byte buffer[] = new byte[1024];

                        OutputStream outputStream = client.getOutputStream();
                        outputStream.write("I am server ".getBytes());
                        outputStream.flush();

                        while(input.available() != -1){
                            System.out.print((char) input.read());
                        }

                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                    System.out.println("新的客户端:client--"+client.toString());
                }).start();

            }
        }



    }

    public static void main(String[] args) throws IOException {
        new MyServerSocket();

    }
}
